<?php

namespace App\Admin\Imports;

use App\Models\SwtBjMachine;
use App\Services\BaoJianService;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithStartRow;

class SwtBjMachineImport implements ToModel, WithStartRow {
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $imei = trim($row[2]);

        $machine = SwtBjMachine::firstWhere('imei', $imei);

        if ($machine) {
            return null;
        }

        $last_machine_code = SwtBjMachine::orderBy('id', 'desc')->value('machine_code');

        $machine_code = $last_machine_code ? $last_machine_code + 1 : '90000001';

        $res = BaoJianService::machineRegister($imei, (string) $machine_code);

        $device_code = $res['deviceCode'];

        return new SwtBjMachine([
            'imei'         => $imei,
            'machine_code' => $machine_code,
            'device_code'  => $device_code,
            'machine_name' => trim($row[1]) ?? '',
            'address'      => trim($row[8]) ?? ''
        ]);
    }

    public function startRow(): int
    {
        return 2;
    }
}
